layui.use(['layer', 'form', 'table', 'util', 'admin', 'tree', 'xmSelect', 'treeTable', 'dropdown', 'laydate', 'notice'], function () {
    var $ = layui.jquery;
    var layer = layui.layer;
    var form = layui.form;
    var table = layui.table;
    var util = layui.util;
    var admin = layui.admin;
    var tree = layui.tree;
    var treeTable = layui.treeTable;
    var xmSelect = layui.xmSelect;
    var dropdown = layui.dropdown;
    var laydate = layui.laydate;
    var notice = layui.notice;
    var selObj, treeData;  // 左树选中数据

    /* 渲染树形 */
    function renderTree() {
        $.get(prefixDept + "/roleTreeData", function (resData) {
            for (var i = 0; i < resData.length; i++) {
                resData[i].spread = true;
                if (resData[i].originObj.status !== "0") {
                    resData[i].title = '<s style="color: #cccccc;">' + resData[i].title + '</s>';
                }
            }
            resData.unshift({id: -1, pId: 0, title: "所有用户", originObj: {deptId: -1, parentId: 0, deptName: "所有用户"}})
            treeData = treeTable.pidToChildren(resData, 'id', 'pid');
            tree.render({
                elem: '#deptTree',
                onlyIconControl: true,
                data: treeData,
                click: function (obj) {
                    selObj = obj;
                    $('#deptTree').find('.ew-tree-click').removeClass('ew-tree-click');
                    $(obj.elem).children('.layui-tree-entry').addClass('ew-tree-click');
                    insTb.reload({
                        where: {deptId: obj.data.id && obj.data.id === -1 ? "" : obj.data.id},
                        page: {curr: 1},
                        url: prefixUser + '/list'
                    });
                }
            });
            $('#deptTree').find('.layui-tree-entry:first>.layui-tree-main>.layui-tree-txt').trigger('click');
        });
    }

    renderTree();

    /* 添加部门 */
    $('#deptAddBtn').click(function () {
        showEditModel(null, selObj ? selObj.data.pid : null);
    });

    /* 修改部门 */
    $('#deptEditBtn').click(function () {
        if (!selObj) return himio.notice.warn('未选择任何部门');
        if (selObj.data.id === -1) return himio.notice.warn("当前节点【" + selObj.data.title + "】不能编辑");
        showEditModel(selObj.data);
    });

    /* 删除部门 */
    $('#deptDelBtn').click(function () {
        if (!selObj) return himio.notice.warn('未选择任何部门');
        if (selObj.data.id === -1) return himio.notice.warn("当前节点【" + selObj.data.title + "】不能删除");
        doDel(selObj);
    });

    /* 显示部门表单弹窗 */
    function showEditModel(mData, pid) {
        admin.open({
            type: 1,
            area: '450px',
            title: (mData ? '修改' : '添加') + '部门',
            content: $('#deptEditDialog').html(),
            success: function (layero, dIndex) {
                // 回显表单数据
                form.val('deptEditForm', mData ? mData.originObj : null);
                // 表单提交事件
                form.on('submit(deptEditSubmit)', function (data) {
                    data.field.parentId = insXmSel.getValue('valueStr') || 0;
                    var loadIndex = layer.load(2);
                    admin.req(mData ? prefixDept + '/edit' : prefixDept + "/add",
                        data.field,
                        function (res) {
                            layer.close(loadIndex);
                            if (res.code === 0) {
                                layer.close(dIndex);
                                himio.notice.success(res.msg);
                                renderTree();
                            } else {
                                himio.notice.error(res.msg);
                            }
                        }, 'post');
                    return false;
                });
                // 渲染上级部门下拉树
                var insXmSel = xmSelect.render({
                    el: '#deptEditParentSel',
                    height: '250px',
                    data: treeData,
                    initValue: mData ? [mData.originObj.parentId] : (pid ? [pid] : []),
                    model: {label: {type: 'text'}},
                    prop: {
                        name: 'title',
                        value: 'id'
                    },
                    radio: true,
                    clickClose: true,
                    tree: {
                        show: true,
                        indent: 15,
                        strict: false,
                        expandedKeys: true
                    }
                });
                // 禁止弹窗出现滚动条
                $(layero).children('.layui-layer-content').css('overflow', 'visible');
            }
        });
    }

    /* 删除部门 */
    function doDel(obj) {
        layer.confirm('确定要删除此部门吗？', {
            skin: 'layui-layer-admin',
            shade: .1
        }, function (i) {
            layer.close(i);
            var loadIndex = layer.load(2);
            $.get(prefixDept + '/remove/' + obj.data.id, function (res) {
                layer.close(loadIndex);
                himio.notice.resp(res, function () {
                    renderTree();
                });
            }, 'json');
        });
    }

    /* 渲染用户表格 */
    var insTb = table.render({
        id: 'deptUserTable',
        elem: '#deptUserTable',
        data: [],
        height: 'full-168',
        page: true,
        toolbar: '#deptUserTbToolBar',
        cellMinWidth: 100,
        cols: [
            [
                {type: 'checkbox'},
                {type: 'numbers'},
                {field: 'loginName', title: '登录账号', sort: true},
                {field: 'userName', title: '用户名称', sort: true},
                {
                    field: 'deptName', title: '部门', templet: function (d) {
                        return d.dept.deptName === null ? "-" : d.dept.deptName;
                    }
                },
                {field: 'phoneNumber', title: '手机号'},
                {
                    field: 'sex', title: '性别', width: 80, templet: function (d) {
                        return showDictLabel(dictSysUserSex, d.sex);
                    }
                },
                {field: 'status', title: '用户状态', templet: '#userStatusTpl', unresize: true},
                {
                    field: 'gmtCreate', title: '创建时间', width: 180, templet: function (d) {
                        return util.toDateString(d.gmtCreate);
                    }, sort: true
                },
                {title: '操作', toolbar: '#deptUserTbBar', align: 'center', width: 200, fixed: 'right'}
            ]
        ],
        done: function (res, curr, count) {
            form.render('select');
            laydate.render({
                elem: '#gmtCreate'
                , type: 'date'
                , range: '-'
                , format: 'yyyy-MM-dd'
            });
            // 表格搜索
            form.on('submit(deptUserTbSearch)', function (data) {
                if (data.field.gmtCreate) {
                    var searchDate = data.field.gmtCreate.split(' - ');
                    data.field.searchParams = {
                        gmtCreateStart: searchDate[0],
                        gmtCreateEnd: searchDate[1]
                    }
                } else {
                    data.field.searchParams = {
                        gmtCreateStart: null,
                        gmtCreateEnd: null
                    }
                }
                data.field.gmtCreate = undefined;
                insTb.reload({where: data.field, page: {curr: 1}});
                return false;
            });
            //导出的下拉菜单
            dropdown.render({
                elem: 'button[lay-event=export]'
                , trigger: 'hover'
                , data: [{
                    title: '导出全部（无过滤）'
                    , id: "exportAll"
                }, {
                    title: '导出全部（过滤搜索）'
                    , id: "exportSearch"
                }, {
                    title: '导出当前页数据'
                    , id: "exportCurrent"
                }]
                , click: function (obj) {
                    var id = obj.id;
                    if (id === "exportSearch") {
                        var data = $("#deptUserTbSearchForm").serializeArray();
                        if (data.gmtCreate) {
                            var searchDate = data.gmtCreate.split(' - ');
                            data.searchParams = {
                                gmtCreateStart: searchDate[0],
                                gmtCreateEnd: searchDate[1]
                            }
                        } else {
                            data.searchParams = {
                                gmtCreateStart: null,
                                gmtCreateEnd: null
                            }
                        }
                        data.gmtCreate = undefined;
                        exportExcel(data);
                    } else if (id === "exportAll") {
                        exportExcel({});
                    } else {
                        exportExcelCurrent(table, res.data);
                    }
                }
            });
        }
    });

    /* 用户表格工具条点击事件 */
    table.on('tool(deptUserTable)', function (obj) {
        if (obj.event === 'edit') { // 修改
            showEditModel2(obj.data);
        } else if (obj.event === 'more') {
            var that = this;
            //更多下拉菜单
            dropdown.render({
                elem: that
                , show: true //外部事件触发即显示
                , data: [{
                    title: '<i class="fa fa-refresh"></i> 重置密码'
                    , id: 'resetPwd'
                }, {
                    title: '<i class="fa fa-trash"></i> 删除用户'
                    , id: 'del'
                }]
                , click: function (data, othis) {
                    //根据 id 做出不同操作
                    if (data.id === 'resetPwd') {
                        showResetPwdModel(obj.data);
                    } else {
                        doDel2(obj);
                    }
                }
                , style: 'margin-left: -28px; box-shadow: 1px 1px 10px rgb(0 0 0 / 12%);' //设置额外样式
            });
        }
    });

    /* 用户表格头工具栏点击事件 */
    table.on('toolbar(deptUserTable)', function (obj) {
        if (obj.event === 'add') { // 添加
            showEditModel2();
        } else if (obj.event === 'del') { // 删除
            var checkRows = table.checkStatus('deptUserTable');
            if (checkRows.data.length === 0) {
                himio.notice.warn("请选择要删除的数据")
                return;
            }
            var ids = checkRows.data.map(function (d) {
                return d.userId;
            });
            doDel2({ids: ids});
        } else if (obj.event === "import") {
            importExcel();
        } else if (obj.event === "export") {
            //此处用 dropdown 的监听事件
        }
    });

    /* 监听用户状态开关 */
    form.on('switch(userStatusFilter)', function (obj) {
        admin.req(prefixUser + "/changeStatus", {
            userId: this.value,
            status: obj.elem.checked ? 0 : 1
        }, function (resp) {
            himio.notice.resp(resp, function () {
                insTb.reload({where: data.field, page: {curr: 1}});
            })
        }, "post");
    });

    /* 显示用户表单弹窗 */
    function showEditModel2(mData) {
        admin.open({
            type: 1,
            area: '745px',
            title: (mData ? '修改' : '添加') + '用户',
            content: $('#deptUserEditDialog').html(),
            success: function (layero, dIndex) {
                if (mData) {
                    $("#loginNameDiv input[name=loginName]").attr("disabled", true);
                    $("#initPass input[name=password]").attr("disabled", true);
                } else {
                    $("#loginNameDiv input[name=loginName]").attr("disabled", false);
                    $("#initPass input[name=password]").attr("disabled", false);
                }
                // 回显表单数据
                form.val('deptUserEditForm', mData);
                // 表单提交事件
                form.on('submit(deptUserEditSubmit)', function (data) {
                    var loadIndex = layer.load(2);
                    admin.req(mData ? prefixUser + '/edit' : prefixUser + '/add'
                        , data.field,
                        function (res) {
                            layer.close(loadIndex);
                            if (0 === res.code) {
                                layer.close(dIndex);
                                himio.notice.success(res.msg, function () {
                                    insTb.reload({page: {curr: 1}});
                                });
                            } else {
                                himio.notice.error(res.msg);
                            }
                        }, "post");
                    return false;
                });
                //渲染弹框中部门下拉树
                var insXmSel = xmSelect.render({
                    el: '#deptUserEditParentSel',
                    height: '250px',
                    data: treeData,
                    name: 'deptId',
                    initValue: mData && mData.deptId ? [mData.deptId] : [],
                    model: {label: {type: 'text'}},
                    prop: {
                        name: 'title',
                        value: 'id'
                    },
                    radio: true,
                    clickClose: true,
                    tree: {
                        show: true,
                        indent: 15,
                        strict: false,
                        expandedKeys: true
                    }
                });
                // 渲染弹框中角色多选下拉框
                var insRoleSel = xmSelect.render({
                    el: '#userEditRoleSel',
                    name: 'roleIds',
                    autoRow: true,
                    layVerify: 'required',
                    layVerType: 'tips',
                    data: allRoles,
                    prop: {
                        name: 'roleName',
                        value: 'roleId'
                    }
                });
                // 渲染弹框中职位多选下拉框
                var insPostSel = xmSelect.render({
                    el: '#userEditPostSel',
                    name: 'postIds',
                    autoRow: true,
                    data: allPost,
                    prop: {
                        name: 'postName',
                        value: 'postId'
                    }
                });
                // 回显选中职位
                if (mData) {
                    admin.req(prefixUser + "/editUserExtraInfo",
                        {userId: mData.userId},
                        function (resp) {
                            insRoleSel.update({data: resp.roles});
                            insPostSel.update({data: resp.posts});
                        });
                }
                // 禁止弹窗出现滚动条
                $(layero).children('.layui-layer-content').css('overflow', 'visible');
            }
        });
    }

    /* 显示重置密码弹窗 */
    function showResetPwdModel(mData) {
        admin.open({
            type: 1,
            title: '重置密码',
            content: $('#resetPwdDialog').html(),
            success: function (layero, dIndex) {
                // 回显表单数据
                form.val('resetPwdEditForm', mData);
                // 表单提交事件
                form.on('submit(resetPwdEditSubmit)', function (data) {
                    var loadIndex = layer.load(2);
                    admin.req(prefixUser + '/resetPwd', data.field, function (res) {
                        layer.close(loadIndex);
                        layer.close(dIndex);
                        himio.notice.resp(res);
                    }, 'post');
                    return false;
                });
                // 禁止弹窗出现滚动条
                $(layero).children('.layui-layer-content').css('overflow', 'visible');
            }
        });
    }

    /* 删除用户 */
    function doDel2(obj) {
        layer.confirm('确定要删除选中用户吗？', {
            skin: 'layui-layer-admin',
            shade: .1
        }, function (i) {
            layer.close(i);
            var loadIndex = layer.load(2);
            admin.req(prefixUser + '/remove', {
                ids: obj.data ? obj.data.userId : obj.ids ? obj.ids.join(',') : ''
            }, function (res) {
                layer.close(loadIndex);
                himio.notice.resp(res, function () {
                    insTb.reload({page: {curr: 1}});
                });
            }, 'post');
        });
    }

    /* 导入 excel 数据 */
    function importExcel() {
        admin.open({
            area: ['400px', '230px'],
            offset: '300px',
            fix: false,
            //不固定
            maxmin: true,
            shade: 0.3,
            title: '导入用户数据',
            content: $('#importUserDialog').html(),
            btn: ['<i class="fa fa-check"></i> 导入', '<i class="fa fa-remove"></i> 取消'],
            // 弹层外区域关闭
            shadeClose: true,
            btn1: function (index, layero) {
                debugger
                var file = layero.find('#file').val();
                if (file === '' || (!file.endWith(".xls") && !file.endWith('.xlsx'))) {
                    himio.notice.warn("请选择后缀为 “xls”或“xlsx”的文件。");
                    return false;
                }
                var index2 = layer.load(2, {shade: false});
                var formData = new FormData(layero.find('form')[0]);
                $.ajax({
                    url: prefixUser + "/importData",
                    data: formData,
                    cache: false,
                    contentType: false,
                    processData: false,
                    type: 'POST',
                    success: function (result) {
                        layer.close(index2);
                        himio.notice.resp(result, function () {
                            insTb.reload({page: {curr: 1}});
                        });
                    }
                });
            }
        });
    }

    /* 导出 excel 数据 */
    function exportExcel(data) {
        layer.confirm("确定导出所有用户数据吗？", function (index) {
            himio.notice.loading("正在导出数据，请稍后...");
            admin.req(prefixUser + "/export", data, function (result) {
                himio.notice.resp(result, function () {
                    layer.close(index);
                    window.location.href = ctx + "common/download?fileName=" + encodeURI(result.data) + "&delete=" + true;
                    notice.destroy();
                });
            }, "post");
        });
    }

    /* 导出当前页 excel 数据 */
    function exportExcelCurrent(table, exportData) {
        var title = ['用户序号', '部门编号', '登录名称', '用户名称', '用户邮箱', '手机号码', '用户性别', '帐号状态'];
        var data = [];
        for (var i = 0; i < exportData.length; i++) {
            data.push([
                exportData[i].userId,
                exportData[i].deptId,
                exportData[i].loginName,
                exportData[i].userName,
                exportData[i].email,
                exportData[i].phoneNumber,
                exportData[i].sex,
                exportData[i].status
            ]);
        }
        table.exportFile(title, data, 'xls');
    }
});

/* 下载导入的 excel模板 */
function downloadTemplate() {
    admin.req(prefixUser + "/importTemplate", function (result) {
        himio.notice.resp(result, function () {
            window.location.href = ctx + "common/download?fileName=" + encodeURI(result.data) + "&delete=" + true;
        })
    }, "get");
}